import { defineEventHandler, readBody } from 'h3'
import { getPool } from '../util/mysql'
import { recordLog } from '../util/log'

function formatDateTime(d: Date | string | null) {
  if (!d) return ''
  const dt = d instanceof Date ? d : new Date(d)
  const y = dt.getFullYear()
  const M = String(dt.getMonth() + 1).padStart(2, '0')
  const D = String(dt.getDate()).padStart(2, '0')
  const h = String(dt.getHours()).padStart(2, '0')
  const m = String(dt.getMinutes()).padStart(2, '0')
  const s = String(dt.getSeconds()).padStart(2, '0')
  return `${y}-${M}-${D} ${h}:${m}:${s}`
}

export default defineEventHandler(async (event: any) => {
  const body = await readBody(event).catch(() => ({}))
  const params = (event.context && event.context.params) || {}
  const amountStr = body.amount ?? params.amount
  // 使用 product_id 作为创建/查找订单的主要入参，支持可选的 product_name
  const productId = body.product_id ?? params.product_id
  const productName = body.product_name ?? params.product_name ?? productId
  const email = (body.email ?? params.email ?? '')

  if (!amountStr || !productId) {
    event.node.res.statusCode = 400
    await recordLog(event, { message: 'createproduct: missing amount or product_id', userId: 0 })
    return { status: 400, message: 'missing amount or product_id' }
  }

  // 邮箱为必填项
  if (!String(email || '').trim()) {
    event.node.res.statusCode = 400
    await recordLog(event, { message: 'createproduct: missing email', userId: 0 })
    return { status: 400, message: 'missing email' }
  }

  const amount = Number(amountStr)
  if (Number.isNaN(amount)) {
    event.node.res.statusCode = 400
    await recordLog(event, { message: 'createproduct: invalid amount', userId: 0 })
    return { status: 400, message: 'invalid amount' }
  }

  try {
    const pool = await getPool()
    // 查找 10 分钟内的未支付订单
    const [rows]: any = await pool.execute(
      `SELECT * FROM lin_order WHERE create_time >= DATE_SUB(NOW(3), INTERVAL 10 MINUTE) AND status = ? AND product_id = ? AND amount = ? AND email = ? AND is_deleted = 0 ORDER BY create_time DESC LIMIT 1`,
      ['未支付', productId, amount, String(email || '')]
    )

    if (Array.isArray(rows) && rows.length > 0) {
      const r = rows[0]
      const ret = {
        payment_no: r.payment_no,
        payment_id: r.payment_id,
        amount: Number(r.amount),
        user_id: r.user_id,
        status: r.status,
        email: r.email,
        create_time: formatDateTime(r.create_time)
      }
      await recordLog(event, { message: `createproduct: found recent order payment_id=${r.payment_id}`, userId: r.user_id || 0 })
      return ret
    }

    // 生成新的订单
  const timestamp = Date.now()
  const orderno = '20250' + timestamp
    const id = (typeof (globalThis as any).crypto !== 'undefined' && (globalThis as any).crypto.randomUUID)
      ? (globalThis as any).crypto.randomUUID()
      : require('crypto').randomUUID()

    const now = new Date()
    await pool.execute(
      `INSERT INTO lin_order (id, payment_no, payment_id, user_id, amount, status, payment_time, product_id, product_name, email, product_info, create_time, is_deleted,is_send_email)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, orderno, timestamp, 0, amount, '未支付', null, productId, productName, String(email || ''), '', now, 0, 0]
    )
    const result = {
      payment_no: orderno,
      payment_id: timestamp,
      amount,
      user_id: 0,
      email: String(email || ''),
      status: '未支付',
      create_time: formatDateTime(now)
    }
    await recordLog(event, { message: `createproduct: created order payment_id=${timestamp} product_id=${productId}`, userId: 0 })
    return result
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event, { message: `createproduct: db error ${String(err?.message || err)}`, userId: 0 })
    return { status: 500, message: 'db error', error: String(err?.message || err) }
  }
})
